import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Solution1234 {
    public int balancedString(String s) {
        int[] need=new int[4];
        Arrays.fill(need,-s.length()/4);
        Map<Character,Integer> map=new HashMap<>();
        map.put('Q',0);
        map.put('W',1);
        map.put('E',2);
        map.put('R',3);
        for (char c : s.toCharArray()) {
            need[map.get(c)]++;
        }
        int l=0,r=s.length(),ans=-1;
        while (l<=r){
            int mid=(l+r)/2;
            int[] f=new int[4];
            boolean check=false;
            for (int i=0;i<s.length();i++){
                f[map.get(s.charAt(i))]++;
                if (i>=mid){
                    f[map.get(s.charAt(i-mid))]--;
                }
                if (f[0]>=need[0] && f[1]>=need[1] && f[2]>=need[2] && f[3]>=need[3]){
                    check=true;
                    break;
                }
            }
            if (check){
                ans=mid;
                r=mid-1;
            }else {
                l=mid+1;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1234().balancedString("QQQW"));
    }
}
